from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

# Create your views here.

from .. import models
from django.core.urlresolvers import reverse




def catesadd(request):
    if request.method=='GET':
        #获取所用的商品分类
        data=models.Cates.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')
        #分配数据
        context={'cateslist':data}
        #加载模板
        return render(request,'myadmin/cates/add.html',context)
    elif request.method=='POST':
        try:
            # 执行添加
            ob=models.Cates()
            ob.name=request.POST.get('name')
            ob.pid=request.POST.get('pid')
            if ob.pid=='0':
                ob.path='0,'
            else:
                # 获取当前所选的分类的path
                fob=models.Cates.objects.get(id=ob.pid)
                ob.path=fob.path+ob.pid+','
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="' + reverse('myadmin_cates_index') + '"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="' + reverse('myadmin_cates_add') + '"</script>')

# 商品分类 列表
def catesindex(request):
    data=models.Cates.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')

    # 获取搜索条件,和参数
    keywords = request.GET.get('keywords')
    if keywords:
        data = data.filter(name__contains=keywords)


    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(data, 5)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p', 1)
    # 获取当前页的数据
    cateslist = paginator.page(p)


    context={'cateslist':cateslist}
    return render(request,'myadmin/cates/index.html',context)


# 分类 删除
def catesdel(request):
    cid=request.GET.get('cid')
    num=models.Cates.objects.filter(pid=cid).count()
    if num:
        return JsonResponse({'error':1,'msg':'当前类下有子类,不能删除'})
    ob=models.Cates.objects.get(id=cid)
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功'})


# 分类的修改
def catesedit(request):
    try:
        # 根据cid获取分类对象
        ob=models.Cates.objects.get(id=request.GET.get('cid'))
        ob.name=request.GET.get('name')
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功'})
    except:
        return JsonResponse({'error':1,'msg':'更新失败'})
